package com.steptime.thread.atomic;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * AtomicIntegerFieldUpdater对普通变量进行原子升级
 * 使用场景：偶尔需要一个原子get-set操作
 */
public class AtomicUpdaterDemo implements Runnable{
    static PlayGame tom = new PlayGame();
    static PlayGame peter =new PlayGame();
    AtomicIntegerFieldUpdater<PlayGame> atomicIntegerFieldUpdater =
            AtomicIntegerFieldUpdater.newUpdater(PlayGame.class, "score");

    public static void main(String[] args) {
        AtomicUpdaterDemo demo = new AtomicUpdaterDemo();
        Thread thread1 = new Thread(demo);
        Thread thread2 = new Thread(demo);
        thread1.start();
        thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("tom score :"+tom.score);
        System.out.println("peter score :"+peter.score);

    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            tom.score++;
            atomicIntegerFieldUpdater.incrementAndGet(peter);
        }
    }

    static class PlayGame{
        volatile int score;
    }
}
